package com.example.springbootusecase.controller;

import com.example.springbootusecase.bo.Product;
import com.example.springbootusecase.bo.ProductEs;
import com.example.springbootusecase.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    // 添加商品
    @PostMapping
    public ProductEs save(@RequestBody ProductEs productEs) {
        return productService.save(productEs);
    }

    // 根据 ID 查询
    @GetMapping("/{id}")
    public Optional<ProductEs> getById(@PathVariable Integer id) {
        return productService.findById(id);
    }

    // 根据 name 查询
    @GetMapping("/search/{name}")
    public ProductEs getByName(@PathVariable String name) {
        return productService.findByName(name);
    }

    // 根据关键字搜索
    @GetMapping("/search/{field}/{keyword}")
    public Object search(@PathVariable String field,@PathVariable String keyword) {
        return productService.search(field,keyword);
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Integer id) {
        productService.deleteById(id);
    }

    @PostMapping("/sync")
    public void syncAllProductsToES() {
        productService.syncAllProductsToES();
    }

    @PostMapping("fix")
    public void fixMissingIsDeletedField() {
        productService.fixMissingIsDeletedField();
    }

}
